package indi.kider.server.applet.service;

import com.alibaba.fastjson.JSON;
import indi.kider.common.constant.*;
import indi.kider.common.model.apabus.Rent;
import indi.kider.common.model.apartment.Community;
import indi.kider.common.model.apartment.Houses;
import indi.kider.common.model.employee.Tenant;
import indi.kider.common.model.woniubus.TenantVo;
import indi.kider.server.apabus.mapper.RentMapper;
import indi.kider.server.apartment.mapper.CommunityMapper;
import indi.kider.server.apartment.mapper.HousesMapper;
import indi.kider.server.employee.mapper.TenantMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import pers.vankid.common.model.base.CommonResponse;
import pers.vankid.common.model.base.CoreException;

import java.util.Date;
import java.util.List;
import java.util.Map;

@SuppressWarnings("ALL")
@Service
public class RentServiceImpl implements RentService {

    @Autowired
    private RentMapper rentMapper;

    @Autowired
    private HousesMapper housesMapper;

    @Autowired
    private CommunityMapper communityMapper;
    @Autowired
    private TenantMapper tenantMapper;

    @Autowired
    private HouseService houseService;


    @Override
    public Rent getTenantHouseInfo(String tenantId) throws Exception {
        Rent rent = new Rent();
        rent.setTenantId(Long.valueOf(tenantId));
        rent.setState(1);
        return rentMapper.selectOne(rent);
    }

    @Override
    public List<Rent> getEmployeeTenantInfo(String houseId) throws Exception {
        Rent rent = new Rent();
        rent.setHousesId(Long.valueOf(houseId));
        rent.setState(1);
        return rentMapper.select(rent);
    }

    /**
     * 承租人租房
     * @param tenantVo
     * @return
     */
    @Transactional(rollbackFor=Exception.class)
    public String rentHouse(TenantVo tenantVo)throws Exception{
        if (tenantVo.getRentDate() == null || tenantVo.getExpireDate() == null)
            throw new CoreException("必须指定入住时间！");
        Long houseId = tenantVo.getHouseId();
        Houses houses = housesMapper.selectByPrimaryKey(houseId);
        // 验证手机号|身份证是否被使用
        checkPhoneOrCardIdIsUse(tenantVo);
        //出租类型
        int comType =  houses.getComType();
        switch (comType){
            case  1://合租--暂不做
                throw new Exception("合租还在建设中---");
            case  2://群租
                // 验证房间是否超员
                checkHouseFull(tenantVo,houses);
                //查询用户是否已存在(根据身份证判断、),已存在则更新
                Tenant tenant = checkUseAddOrUpdate(tenantVo);
                //保存出租关系
                saveRent(tenantVo,houses,tenant.getId(),tenantVo.getOpInId());
                /*修改房屋状态*/
                houses.setState(HouseStateCons.RENTED); //1,空置 2,已租 3，配置中
                houses.setReleaseState(HouseReserveCons.NO_RESRVE); // 未发布状态
                Map<String,Object> map =  houseService.getHouseUserCntMap(houseId);
                //{ inSumCnt:3,inManCnt:1,inFemanCnt:2}
                int inSumCnt = Integer.valueOf(map.get("inSumCnt")+"");
                int inManCnt = Integer.valueOf(map.get("inManCnt")+"");
                int inFemanCnt = Integer.valueOf(map.get("inFemanCnt")+"");
//                inSumCnt ++ ;
//                if(tenant.getSex() == 1){//男
//                    inManCnt ++;
//                }else{
//                    inFemanCnt ++;
//                }
                if(inManCnt>0&&inFemanCnt>0){
                    if(tenantVo.getSex() == TenantSexTypeCons.SEX_MAN){
                        throw new CoreException("该房屋目前只能入住【女】");
                    }else{
                        throw new CoreException("该房屋目前只能入住【男】");
                    }
                }
                houses.setInSumCnt(inSumCnt);
                houses.setInManCnt(inManCnt);
                houses.setInFemanCnt(inFemanCnt);
                housesMapper.updateByPrimaryKeySelective(houses);
                //调用 账单接口=========================
                break;
            default:
                throw new CoreException("暂时只支持群租入住---");
        }
        return "入住办理成功!";
    }


    /**
     * 验证手机号|身份证是否被使用
     */
    private void checkPhoneOrCardIdIsUse(TenantVo tenantVo)throws CoreException {
        Rent query = new Rent();
        query.setTenantTel(tenantVo.getPhone());
        query.setState(RentStateCons.VALID);
        List<Rent> rentList = rentMapper.select(query);
        if (rentList != null && !rentList.isEmpty()){
            Rent temp = rentList.get(0);
            throw new CoreException("当前手机号已被使用，使用方公寓:"+temp.getCommunity()+"-"+temp.getHouseNumb()+"-"+temp.getTenantName());
        }
        query = new Rent();
        query.setCardId(tenantVo.getCardId());
        query.setState(RentStateCons.VALID);
        rentList = rentMapper.select(query);
        if (rentList != null && !rentList.isEmpty()){
            Rent temp = rentList.get(0);
            throw new CoreException("当前身份证已被使用，使用方公寓:"+temp.getCommunity()+"-"+temp.getHouseNumb()+"-"+temp.getTenantName());
        }
    }

    /**
     * 验证房间是否超员
     * @param tenantVo
     * @throws CoreException
     */
    private void checkHouseFull(TenantVo tenantVo,Houses houses)throws CoreException{
        Rent tempRent = new Rent();
        tempRent.setHousesId(houses.getId());
        tempRent.setState(RentStateCons.VALID);
        int rentMaxCnt = rentMapper.selectCount(tempRent);//查看房间已有几人
        if(houses.getMaxCnt() <= rentMaxCnt){
            throw new CoreException("该房间已住满，已入住"+rentMaxCnt+"人!");
        }
    }

    /**
     * 查询用户是否已存在(根据身份证、用户姓名判断、),已存在则更新
     */
    private Tenant checkUseAddOrUpdate(TenantVo tenantVo){
        Tenant tenant = JSON.parseObject(JSON.toJSONString(tenantVo),Tenant.class);
        tenant.setState(StatusCons.VALID);//有效
        tenant.setType(TenantTypeCons.TENANT);//租客
        Tenant tempTenant = new Tenant();
        tempTenant.setCardId(tenantVo.getCardId());
        tempTenant.setState(2);//1:有效2：无效  3注册
        List<Tenant> tenantList =  tenantMapper.select(tempTenant);
        if (tenantList != null && !tenantList.isEmpty()){//已存在则更新用户信息
            tenant.setId(tenantList.get(0).getId());
            tenant.setPwd("123456");
            tenantMapper.updateByPrimaryKeySelective(tenant);
        }else{
            tempTenant = new Tenant();
            tempTenant.setCardId(tenantVo.getCardId());
            tempTenant.setState(3);//1:有效2：无效 3注册
            tenantList =  tenantMapper.select(tempTenant);
            if (tenantList != null && !tenantList.isEmpty()){//已存在则更新用户信息
                tenant.setId(tenantList.get(0).getId());
                tenant.setPwd("123456");
                tenantMapper.updateByPrimaryKeySelective(tenant);
            }else{
                tenant.setId(null);
                tenantMapper.insertSelective(tenant);
            }
        }
        return tenant;
    }
    /**
     * 保存出租关系
     * @param tenantVo
     * @param houses
     * @param tenantId
     */
    private void saveRent(TenantVo tenantVo,Houses houses,Long tenantId,Long opInId){
        /*保存rent表 出租关系*/
        Rent rent = JSON.parseObject(JSON.toJSONString(houses),Rent.class);
        Community community = communityMapper.selectByPrimaryKey(houses.getCommunityId());
        rent.setHousesId(houses.getId());
        rent.setTenantId(tenantId);
        rent.setRentDate(tenantVo.getRentDate());
        rent.setExpireDate(tenantVo.getExpireDate());
        rent.setPriceSet(tenantVo.getPriceSet());//租金取页面输入的租金
        rent.setRemark(tenantVo.getRemark());
        rent.setTenantName(tenantVo.getName());
        rent.setTenantTel(tenantVo.getPhone());
        rent.setState(RentStateCons.VALID);//1租住 3搬离
        rent.setCommunity(community.getCommunity());
        rent.setAddress(community.getAddress());
        rent.setCardId(tenantVo.getCardId());
        rent.setOpInId(opInId);
        rent.setOpInTime(new Date());
        rent.setId(null);
        rentMapper.insertSelective(rent);
    }
}
